package scala.day03

import scala.io.Source

object Demo03StudentTest {
  def main(args: Array[String]): Unit = {
    /**
      * 统计总分排名前十的学生
      */
    //读数据
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList
    //取数据
    val idAndScore: List[(String, Double)] = scores.map(f => {
      val split: Array[String] = f.split(",")
      (split(0),split(2).toDouble)
    })
    val idAndName: List[(String, String)] = students.map(f => {
      val split: Array[String] = f.split(",")
      (split(0),split(1))
    })
    //按照学号分组
    val group: Map[String, List[(String, Double)]] = idAndScore.groupBy(i => i._1)
    //统计学生的总分
    val idAndSum: Map[String, Double] = group.map(kv => {
      val id: String = kv._1
      //取出一个人所有的分数
      val doubles: List[Double] = kv._2.map(kv1 => kv1._2)
      //计算总分
      val sum: Double = doubles.sum
      (id,sum)
    })
    val nameAndScore: List[(String, Double)] = idAndName.map(f => {
      //学生id
      val id: String = f._1
      val name: String = f._2
      val d : Double = idAndSum.getOrElse(id,0)
      (name,d)
    })
    nameAndScore.sortBy(f => -f._2).take(10).foreach(println)
  }
}
